package dao

import (
	"go_server/game_server/database/mysql"
	"go_server/game_server/util"
	"go_server/zinx/zlog"
	"gorm.io/datatypes"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type BagInfo struct {
	RoleId int64 `gorm:"column:role_id;primary"`
	Items datatypes.JSONType[map[int32]int32] `gorm:"column:items"`
	Currency datatypes.JSONType[map[int32]int32] `gorm:"column:currency"`
}

func (BagInfo) TableName() string {return "bag_info"}

var (
	all_bag_info_field = util.GetGormFields(BagInfo{})
)

func GetBagInfoByRoleId(roleId int64) *BagInfo {
	db := mysql.GetServerDBConnection()
	var bagInfo BagInfo
	if err := db.Select(all_bag_info_field).Where("role_id=?", roleId).First(&bagInfo).Error; err != nil {
		if err != gorm.ErrRecordNotFound { zlog.Errorf("GetBagInfoByRoleId ERR!!! roleId: %d, err: %v",
			roleId, err)}
		return nil
	}
	return &bagInfo
}

func NewOrUpdateBagInfo(itemMap map[int32]int32, currencyMap map[int32]int32, roleId int64) {
	if itemMap == nil {
		itemMap = make(map[int32]int32)
	}
	if currencyMap == nil {
		currencyMap = make(map[int32]int32)
	}
	bagInfoObj := &BagInfo{
		RoleId: roleId,
		Items: datatypes.NewJSONType(itemMap),
		Currency: datatypes.NewJSONType(currencyMap),
	}

	db := mysql.GetServerDBConnection()
	if err := db.Clauses(clause.OnConflict{
		Columns: []clause.Column{{Name: "role_id"}},
		DoUpdates: clause.AssignmentColumns([]string{"items", "currency"}),
	}).Create(bagInfoObj).Error; err != nil {
		zlog.Errorf("create or update BagInfo %v data failed: %v", bagInfoObj, err)
	}
}
